// pages/enrolldata/enrolldata.js
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    id:'',
    item:{},
    extras:[],
    showSex:false,
    fullName:'',
    phoneNumber:'',
    companyName:'',
    addNumber:'',
    joinNumber:0,
    idNumber:'',
    mailbox:'',
    address:'',
    inputVal:[],
    sex:'',
    customArray:[],
    number:0,
    perUpperLimit:0,
    isbtn:false
  },
  //活动详情
  getdata(){
    var that = this
    app.req({
      url: "wechat/activity/activityDetail",
      method: "post",
      data: {
        id: that.data.id,
      },
      success: function (res) {
        if (200 == res.code) {
          console.log("详情",res)
          that.setData({
            item:res.data
          })
          var arr = []
          var extras =[]
          var item = ""
          for (let i = 0; i < that.data.item.extras.length; i++) {
            if (that.data.item.extras[i].isChoose==1){
              arr.push(item)
              extras.push(that.data.item.extras[i])
            }
            that.setData({
              inputVal: arr,
              extras: extras
            })
          }
          that.setData({
            isbtn: true
          })
          console.log("inputVal--", that.data.inputVal)
        } else {
          wx.showToast({
            title: res.msg,
            icon: 'none',
            duration: 2000
          })
        }
      }
    });
  },

  inputBindname: function (e) {
    this.setData({
      fullName: e.detail.value
    })
  },
  selectToItemSex: function (event) {
    var that = this;
    var data = event.currentTarget.dataset;
    that.setData({
      sex: data.id,
      showSex:false,
    })
  },
  inputBindpnone: function (e) {
    this.setData({
      phoneNumber: e.detail.value
    })
  },
  getPhoneNumber: function (e) {//点击获取手机号码按钮
    var that = this;
    console.log('点击手机号')
    var phone = wx.getStorageSync('phone');
    console.log(phone);
    that.setData({ phoneNumber: phone })
    // wx.login({
    //   success: (res) => {
    //     var ency = e.detail.encryptedData;
    //     var iv = e.detail.iv;
    //     var sessionk = that.data.sessionKey;
    //     if (e.detail.errMsg == 'getPhoneNumber:fail user deny') {
    //       that.setData({
    //         modalstatus: true
    //       });
    //     } else {//同意授权
    //       app.req({
    //         method: "post",
    //         url: 'wechat/sysMessage/deciphering',
    //         data: {
    //           encrypdata: ency,
    //           ivdata: iv,
    //           code: res.code
    //         },
    //         header: {
    //           'content-type': 'application/json' // 默认值
    //         },
    //         success: (res) => {
    //           console.log("解密成功~~~~~~~将解密的号码保存到本地~~~~~~~~");
    //           console.log(res);
    //           var phone = res.data.telPhone;
    //           console.log(phone);
    //           that.setData({ phoneNumber: phone })
    //         }, fail: function (res) {
    //           console.log("解密失败~~~~~~~~~~~~~");
    //           console.log(res);
    //         }
    //       });
    //     }
    //   }
    // })
  },
  inputBindcompany: function (e) {
    this.setData({
      companyName: e.detail.value.replace(/\s+/g, '')
    })
  },
  inputBindnumber: function (e) {
    console.log('随行人数', e.detail.value)
    e.detail.value = e.detail.value.replace(/^[0]+[0-9]*$/gi, "0");
    if (e.detail.value.indexOf(".") > 0) {
      e.detail.value = ''
    } if (e.detail.value.indexOf(".") == 0) {
      e.detail.value = e.detail.value.replace(/[^$#$]/g, "");
    }
    this.setData({
      addNumber: e.detail.value,
      joinNumber: e.detail.value
    })
  },
  inputBindIdcard: function (e) {
    this.setData({
      idNumber: e.detail.value
    })
  },
  inputBindEmail: function (e) {
    this.setData({
      mailbox: e.detail.value.trim()
    })
  },
  inputBindAddress: function (e) {
    this.setData({
      address: e.detail.value.replace(/\s+/g, '')
    })
  },
  //自定义
  inputBindcustom: function (e) {
    var nowIdx = e.currentTarget.dataset.index;//获取当前索引
    var val = e.detail.value.replace(/\s+/g, '');//获取输入的值
    var oldVal = this.data.inputVal;
    console.log("oldVal", oldVal)
    oldVal[nowIdx] = val;//修改对应索引值的内容
    this.setData({
      inputVal: oldVal
    })

  },
  showSexSelect: function () {
    this.setData({
      showSex:true
    })
  },
  //继续报名
  continueSignUp: function () {
    var that = this
    that.toggle("item.perCapita", "");
    that.toggle("outTradeNo", "");
    that.setData({
      paymentAmount: 0,
      payWindow: false
    })
    that.goToRegisterPage();
  },

  //支付金额
  paymentMoney: function () {
    var that = this
    if (that.data.paymentAmount.length == 0) {
      wx.showToast({
        title: "请输入支付金额",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.paymentAmount == 0) {
      wx.showToast({
        title: "支付金额不能为0",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.paymentAmount <= 0.01) {
      wx.showToast({
        title: "支付金额需大于0.01元",
        icon: 'none',
        duration: 2000
      })
      return
    }
    if (that.data.paymentAmount > 0.01) {
      that.setData({
        payWindow: false,
        show: true
      })
      // that.addToActivity()
    }
  },

  //确定报名
  confirmSignUp: function (e) {
    var that = this;
    console.log('立即报名')
    // that.data.formId = e.detail.formId;
      if (that.data.item.isName == 1) {
        if (that.data.fullName.length == 0) {
          wx.showToast({
            title: "请输入姓名",
            icon: 'none',
            duration: 2000
          })
          return
        }
      }
    if (that.data.item.isSex == 1) {
      if (that.data.sex== '') {
        wx.showToast({
          title: "请选择性别",
          icon: 'none',
          duration: 2000
        })
        return
      }
    }
      if (that.data.item.isTelphone == 1) {
        if (that.data.phoneNumber.length == 0) {
          wx.showToast({
            title: "请输入手机号",
            icon: 'none',
            duration: 2000
          })
          return
        }
        if (!(/^1[3456789]\d{9}$/.test(that.data.phoneNumber))) {
          wx.showToast({
            title: '请输入正确的手机号格式',
            icon: 'none',
            duration: 2000
          })
          return;
        }
      }
      if (that.data.item.isCompany == 1) {
        if (that.data.companyName.length == 0) {
          wx.showToast({
            title: "请输入公司名称",
            icon: 'none',
            duration: 2000
          })
          return
        }
      }
      if (that.data.item.isEnrollment == 1) {
        if (that.data.joinNumber.length == 0) {
          wx.showToast({
            title: "请输入随行人数",
            icon: 'none',
            duration: 2000
          })
          return
        }
        if (that.data.joinNumber < 0) {
          wx.showToast({
            title: "请输入随行人数",
            icon: 'none',
            duration: 2000
          })
          return
        }

        if (that.data.joinNumber > 999) {
          wx.showToast({
            title: "报名人数超过上限",
            icon: 'none',
            duration: 2000
          })
          return
        }
      }

      if (that.data.item.isIdcard == 1) {
        if (that.data.idNumber.length == 0) {
          wx.showToast({
            title: "请输入身份证号码",
            icon: 'none',
            duration: 2000
          })
          return
        }


        if (!(/(^\d{15}$)|(^\d{18}$)|(^\d{17}(\d|X|x)$)/.test(that.data.idNumber))) {
          wx.showToast({
            title: '身份证号码有误',
            duration: 2000,
            icon: 'none'
          });
          return
        }
      }
      var emailPattern = new RegExp("^[a-z0-9]+([._\\-]*[a-z0-9])*@([a-z0-9]+[-a-z0-9]*[a-z0-9]+.){1,63}[a-z0-9]+$");
      if (that.data.item.isEmail == 1) {
        if (that.data.mailbox.length == 0) {
          wx.showToast({
            title: "请输入邮箱",
            icon: 'none',
            duration: 2000
          })
          return
        }


        if (!emailPattern.test(that.data.mailbox)) {
          wx.showToast({
            title: "邮箱格式错误",
            icon: 'none',
            duration: 2000
          })
          return;
        }
      }
      if (that.data.item.isAddress == 1) {
        if (that.data.address.length == 0) {
          wx.showToast({
            title: "请输入地址",
            icon: 'none',
            duration: 2000
          })
          return
        }
      }

      var participationArray = []
      //判断第几个元素是空的
      for (let i = 0; i < that.data.inputVal.length; i++) {
        var item = that.data.extras[i]
        if (that.data.inputVal[i] == "") {
          console.log(item.fields + "为空", that.data.inputVal);
          wx.showToast({
            title: '请输入'+item.fields,
            icon: 'none',
            duration: 2000
          })
          return
        }
        var dict = {
          fields: item.fields,
          dataType: "String",
          fieldsContent: that.data.inputVal[i]
        }
        participationArray.push(dict)
        that.setData({
          customArray: participationArray
        })
      }
    if (that.data.perUpperLimit >0){
      var num = parseInt(that.data.number) +  parseInt(that.data.joinNumber) + 1
      console.log('人员上限', num)
      if (that.data.perUpperLimit < num) {
        wx.showToast({
          title: "人员已超上限，请联系活动发起人",
          icon: 'none',
          duration: 2000
        })
        return
      }
    }
      let pages = getCurrentPages(),
        prevPage = pages[pages.length - 2];
        prevPage.setData({
          fullName: that.data.fullName,
          phoneNumber: that.data.phoneNumber,
          companyName: that.data.companyName,
          addNumber: that.data.addNumber,
          joinNumber: that.data.joinNumber,
          idNumber: that.data.idNumber,
          mailbox: that.data.mailbox,
          address: that.data.address,
          inputVal: that.data.inputVal,
          sex: that.data.sex,
          customArray: that.data.customArray,
          isOpen:true,
      　　})
        wx.navigateBack({
          delta: 1
        })
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    var that = this
    that.setData({
      id: options.id,
      fullName: options.fullName,
      phoneNumber: options.phoneNumber,
      companyName: options.companyName,
      addNumber: options.addNumber,
      joinNumber: options.joinNumber,
      idNumber: options.idNumber,
      mailbox: options.mailbox,
      address: options.address,
      sex: options.sex,
      // customArray: options.customArray,
      perUpperLimit: options.perUpperLimit,
      number: options.number
    })
    console.log('自定义', that.data.customArray)
    that.getdata()
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})